package com.hz.house.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hz.house.common.ResultUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;

@Service
public class FileUploadService {

	@Resource
	private RestTemplate ribbonTemplate;
	  
	  //上传图片并校验内容是否是敏感的部分
	  public Object uploadFile(HttpServletRequest req,MultipartFile[] file) {
		  
		  
		  getXiaoChengxuToken();
		  
			return null;
	  }
	  
	  //
	  private String getXiaoChengxuToken() {
		  String url = "http://house-small-building/ms/building/getXiaoChengxuTk";
		  String res = this.ribbonTemplate.getForObject(url, String.class);
		  JSONObject jo = JSON.parseObject(res);
		  return  jo.getString("data");
	  }
	  
	  private static Logger logger = LoggerFactory.getLogger(FileUploadService.class);
	    private static final String ACCESS_KEY ="AKID7365oJHlilplYBmEfuyvfDfrUExTArfC";
	    private static final String SECRET_KEY ="avqX0NULwJUmpTv61f5I5hc5RXMufJgp";
	    //private static final String APP_ID = "1258778894";
	    private static final String BASE_URL = "https://house-dev-img-1258778894.cos.ap-chengdu.myqcloud.com/";
		
		
	    
	    
	    /**
	     * 	上传文件
	     * @param req
	     * @param file
	     * @return
	     */
		public Object upload(HttpServletRequest req,MultipartFile file) {
			
			if(file.getSize()>1024*1024L)
				return ResultUtil.fail("图片不能超过1M哦");
			//校验图片是否敏感
			
			COSClient cosc = getCosClient();
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");
			SimpleDateFormat sdfx = new SimpleDateFormat("yyyyMMdd");
			String url = "";
			try {
                String originalFilename = file.getOriginalFilename();
                String subfix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                String fileName = sdf.format(new Date())+(new Random()).nextInt(9)+"."+subfix;
                String key =sdfx.format(new Date())+"/"+fileName;//文件唯一名称
                PutObjectRequest putObjectRequest = new PutObjectRequest("house-dev-img-1258778894", 
                		key, file.getInputStream(),new ObjectMetadata());
                cosc.putObject(putObjectRequest);//提交上传
                url = BASE_URL+key;
	        } catch (Exception e) {
	        	e.printStackTrace();
	        	logger.error("上传文件异常",e);
	        }finally {
	        	cosc.shutdown();
	        }
			return ResultUtil.ok(url);
		}
		
		
		
		private COSClient getCosClient() {
			// 1 初始化用户身份信息 secretId,SECRET_KEY
	        COSCredentials cred = new BasicCOSCredentials(ACCESS_KEY,SECRET_KEY );
	        // 2 设置bucket的区域
	        ClientConfig clientConfig = new ClientConfig(new Region("ap-chengdu"));
	        // 3 生成 cos 客户端。
	        COSClient cosClient = new COSClient(cred, clientConfig);
	        return cosClient;
		}
}
